package com.jy.admin.services.cashPocket;

import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.jy.admin.config.ApolloConfigUtil;
import com.jy.admin.db.dao.*;
import com.jy.admin.db.entity.*;
import com.jy.admin.enums.*;
import com.jy.admin.jobs.BaseJobHandler;
import com.jy.admin.services.BaseCrawlerService;
import com.jy.admin.services.cashPocket.vo.ClOrderInputVo;
import com.jy.admin.services.cashPocket.vo.ClOrderReceiveRequest;
import com.jy.admin.services.cashPocket.vo.ClRepaymentRequest;
import com.jy.admin.services.cashPocket.vo.ClUserInfoInputVo;
import com.jy.bo.common.conf.util.HttpUtil;
import com.robert.vesta.util.IdUtils;
import okhttp3.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2022/1/3
 * Time: 8:46 下午
 */
@Service
public class HiRupeeService extends BaseCrawlerService {
    private static final Logger LOGGER = LoggerFactory.getLogger(HiRupeeService.class);

    @Autowired
    private CeOrdersDetailDao ordersDetailDao;

    @Autowired
    private CeMerchantDao merchantDao;

    @Autowired
    private CeCommentPushLogDao commentPushLogDao;

    @Autowired
    private CeAgentAccountDao agentAccountDao;

    @Autowired
    private ApolloConfigUtil apolloConfigUtil;

    @Autowired
    private CeRepaymentLinkDao repaymentLinkDao;

    @PostConstruct
    public void init() {
        BaseJobHandler.merchantAndServiceMap.put("hirupeeOA", this);
        BaseJobHandler.merchantAndServiceMap.put("antidOE", this);
        BaseJobHandler.merchantAndServiceMap.put("rupeeparkOC", this);
    }

    public boolean autoLogin(CeAgentAccountEntity agentAccount) {
        if (apolloConfigUtil.isAutoLoginOpen()) {
            CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
            String url = merchant.getApiDomain() + "/cms/login";
            LOGGER.info("== 开始请求登录接口 ==,url:{}", url);
            Map<String, String> headers = Maps.newHashMap();
            JSONObject params = new JSONObject();
            params.put("phone", agentAccount.getAccount());
            params.put("password", agentAccount.getPassword());
            String result = HttpUtil.postPageSsLText(url, headers, params.toString());
            LOGGER.info("== HiRupee请求登录接口 ==,result:{}", result);
            if (JsonIterator.deserialize(result).get("code").toInt() == 200) {
                LOGGER.error("== 请求登录接口 成功==，data:{}", JsonIterator.deserialize(result).get("data").toString());
                JSONObject requestHeader = new JSONObject();
                requestHeader.put("x-app-token", JsonIterator.deserialize(result).get("data").get("token").toString());
                requestHeader.put("Content-Type", "application/json");
                agentAccount.setRequestHeader(requestHeader.toString());
                agentAccount.setLoginDt(new Date());
                agentAccount.setLoginStatus(1);
                agentAccountDao.updateByPrimaryKey(agentAccount);
                return true;
            } else {
                LOGGER.info("== 请求登录接口 失败 ==");
                agentAccount.setLoginStatus(2);
                agentAccountDao.updateByPrimaryKey(agentAccount);
                return false;
            }
        } else {
            LOGGER.info("== 请求登录接口 开关未开启 ==");
            agentAccount.setLoginStatus(2);
            agentAccountDao.updateByPrimaryKey(agentAccount);
        }
        return false;
    }

    @Override
    public boolean hasLogin(CeAgentAccountEntity agentAccount) {
        if (apolloConfigUtil.isLoginStatusUseCache()) {
            return agentAccount.getLoginStatus() == 1;
        }

        if (agentAccount.getLoginStatus() == 2) {
            LOGGER.error("== 账号 token不可用 ==,account:{}", agentAccount.getAccount());
            boolean isLogin = autoLogin(agentAccount);
            if (!isLogin) {
                return false;
            }
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String url = merchant.getApiDomain() + "/cms/users/route";
        LOGGER.info("== 开始检测Token是否有效 ==,url:{}", url);

        Map<String, String> headers = getHeaders(agentAccount);
        Map<String, String> params = Maps.newHashMap();
        String result = HttpUtil.getPageSSL(url, params, headers);
        LOGGER.info("== 结束检测Token是否有效 ==,result:{}", result);

        if (JsonIterator.deserialize(result).get("code").toInt() != 200) {
            LOGGER.error("== 请求接口数据出错 当前账号token无效==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.user_info.getType());
            return autoLogin(agentAccount);
        }
        return true;
    }

    @Override
    public void refresh(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== InfinityCashService 开始刷新数据 ==,account:{}", agentAccount.getAccount());
        updateOrderList(agentAccount);

        LOGGER.info("== 订单数据更新完成 开始更新订单关联数据==，account:{}", agentAccount.getAccount());
        updateOrderDetailInfo(agentAccount);

        LOGGER.info("== 订单关联数据已经更新完成==，account:{}", agentAccount.getAccount());
    }


    @Override
    public void updateOrderList(CeAgentAccountEntity agentAccount) {
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String url;
        if (agentAccount.getStage().contains("d")) {
            url = merchant.getApiDomain() + "/cms/preCollection/tasks/my?pageIndex=1&pageSize=200";
        }else {
            url = merchant.getApiDomain() + "/cms/collection/tasks/my?pageIndex=1&pageSize=200";
        }
        LOGGER.info("== 开始请求订单列表 ==,url:{}", url);
        Map<String, String> headers = getHeaders(agentAccount);
        Map<String, String> params = Maps.newHashMap();
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));
        String result = HttpUtil.getPageSSL(url, params, headers);
        if (JsonIterator.deserialize(result).get("code").toInt() != 200) {
            LOGGER.error("== 订单列表请求接口数据出错 ==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
            return;
        }

        List<Any> resultsList = JsonIterator.deserialize(result).get("data").get("list").asList();
        LOGGER.info("== 未还款订单列表 ==,screeningList:{}", JsonStream.serialize(resultsList));
        LOGGER.info("== 未还款订单列表数量 ==,size:{}", resultsList.size());

        //查询今天该账号的所有有效订单
        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());

        //更新数据
        LOGGER.info("==当天已经有数据 ==，size:{}", activeOrders.size());

        resultsList.forEach(item -> {
            try {
                String orderNo = item.get("orderID").toString();
                CeOrdersEntity OneByOrderNo = ordersDao.getTodayOneByOrderNoAndAgentCode(orderNo, agentAccount.getAgentCode());
                if (OneByOrderNo == null) {
                    LOGGER.info("== 列表为空,插入订单 ==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), orderNo);
                    CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                            .setAgentCode(agentAccount.getAgentCode())
                            .setMerchantCode(agentAccount.getMerchantCode())
                            .setOrderNo(orderNo)
                            .setOrderInfo(item.toString())
                            .setStatus(OrderStatusEnum.active.getStatus())
                            .setCreateDt(new Date())
                            .setCollectionNo(IdUtils.genId() + "");
                    ordersDao.insert(ceOrdersEntity);
                } else {
                    LOGGER.info("== 订单已存在 ==,agentCode:{},orderNo:{}", agentAccount.getAgentCode(), orderNo);
                }
            } catch (Exception e) {
                LOGGER.error("== 插入数据发生异常 ==,account:{},loanId:{}", agentAccount.getAccount(), item.get("loanAppId").toString(), e);
            }
        });


        LOGGER.info("== 开始检测订单变化 ==，size:{}", resultsList.size());
        activeOrders.forEach(item -> {
            try {
                String id = JsonIterator.deserialize(item.getOrderInfo()).get("orderID").toString();
                boolean hasOrder = false;
                for (int i = 0; i < resultsList.size(); i++) {
                    Any child = resultsList.get(i);
                    String orderNo = child.get("orderID").toString();
                    if (id.equals(orderNo)) {
                        LOGGER.info("== 当前订单存在 ==,account:{},orderNo:{}", agentAccount.getAccount(), orderNo);
                        hasOrder = true;
                        break;
                    }

                }
                if (!hasOrder) {
                    LOGGER.info("== 当前订单不存在 ==,account:{},orderNo:{}", agentAccount.getAccount(), id);
                    if (item.getStatus().equals(OrderStatusEnum.active.getStatus())) {
                        item.setStatus(OrderStatusEnum.updated.getStatus());
                        ordersDao.updateByPrimaryKey(item);
                    }
                }
            } catch (Exception e) {
                LOGGER.error("== 插入数据发生异常 ==,account:{},orderNo:{}", agentAccount.getAccount(), JsonIterator.deserialize(item.getOrderInfo()).get("id").toString(), e);
            }
        });
        LOGGER.info("== 订单刷新处理完成 ==");
    }

    @Override
    public void updateOrderDetailInfo(CeAgentAccountEntity agentAccount) {

        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());
        if (CollectionUtils.isEmpty(activeOrders)) {
            return;
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());

        Map<String, String> headers = getHeaders(agentAccount);
        Map<String, String> params = new HashMap<>();
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));

        activeOrders.forEach(order -> {

            try {
                boolean hasDetailData = order.getDetailStatus() == 1;
                Map<String, String> infoMap = new HashMap<>();


                Any orderInfo = JsonIterator.deserialize(order.getOrderInfo());
                String orderId = orderInfo.get("orderID").toString();
                String preCollectionID;
                if (agentAccount.getStage().contains("d")){
                    preCollectionID = orderInfo.get("preCollectionID").toString();
                }else {
                    preCollectionID = orderInfo.get("collectionID").toString();
                }

                String repaymentInfoUrl = merchant.getApiDomain() + "/cms/order/tasks/orderInfo?caseID=" + preCollectionID;
                String repaymentInfoResult = HttpUtil.getPageSSL(repaymentInfoUrl, params, headers);
                if (JsonIterator.deserialize(repaymentInfoResult).get("code").toInt() != 200) {
                    LOGGER.info("== 获取repaymentInfo失败==,res:{}", repaymentInfoResult);
                }
                LOGGER.info("== 获取成功 repaymentInfo==");
                Any repaymentInfo = JsonIterator.deserialize(repaymentInfoResult).get("data");
                infoMap.put("repaymentInfo", repaymentInfo.toString());
                String remainMoney = repaymentInfo.get("balanceAmount").toString().equals("") ? "0" : new BigDecimal(repaymentInfo.get("balanceAmount").toString()).divide(new BigDecimal(100)).toString();
                LOGGER.info("== 还款金额 remainMoney==,remainMoney:{},orderNo:{}", orderId, remainMoney);
                updateRemainMoney(order.getCollectionNo(), remainMoney);


                if (!hasDetailData) {
                    CeOrdersDetailEntity baseInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "baseInfo", order.getOrderNo());
                    if (baseInfoDetail == null) {
                        String baseInfoUrl = merchant.getApiDomain() + "/cms/order/tasks/basicInfo?caseID=" + preCollectionID;
                        String baseInfo = HttpUtil.getPageSSL(baseInfoUrl, params, headers);
                        infoMap.put("baseInfo", JsonIterator.deserialize(baseInfo).get("data").toString());
                        LOGGER.info("== 获取成功 baseInfo==");

                        Any userInfo = JsonIterator.deserialize(baseInfo).get("data");
                        List<String> images = Lists.newArrayList();
                        if (!userInfo.get("cidFront").toString().equals("")) {
                            images.add(userInfo.get("cidFront").toString());
                        }
                        if (!userInfo.get("cidReverse").toString().equals("")) {
                            images.add(userInfo.get("cidReverse").toString());
                        }
                        if (!userInfo.get("panFront").toString().equals("")) {
                            images.add(userInfo.get("panFront").toString());
                        }
                        infoMap.put("images", JsonStream.serialize(images));
                        LOGGER.info("== 获取成功 images==");
                    } else {
                        baseInfoDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(baseInfoDetail);
                    }

                    CeOrdersDetailEntity contactInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactInfo", order.getOrderNo());
                    if (contactInfoDetail == null) {
                        String contactInfoUrl = merchant.getApiDomain() + "/cms/order/tasks/emergencyInfo?caseID=" + preCollectionID;
                        String contactInfo = HttpUtil.getPageSSL(contactInfoUrl, params, headers);
                        LOGGER.info("== 获取成功 emergencyInfo==");
                        infoMap.put("contactInfo", JsonIterator.deserialize(contactInfo).get("data").get("emergencyInfo").toString());
                    } else {
                        contactInfoDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(contactInfoDetail);
                    }

                    CeOrdersDetailEntity contactUrlDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactUrl", order.getOrderNo());
                    if (contactUrlDetail == null) {
                        String contactInfoUrl = merchant.getApiDomain() + "/cms/order/tasks/contactInfo?caseID=" + preCollectionID + "&pageIndex=1&pageSize=10";
                        String contactInfo = HttpUtil.getPageSSL(contactInfoUrl, params, headers);
                        String total = JsonIterator.deserialize(contactInfo).get("data").get("total").toString();
                        LOGGER.info("== 获取通讯录总条数 ==,total:{}", total);

                        String contactInfoUrlAgain = merchant.getApiDomain() + "/cms/order/tasks/contactInfo?caseID=" + preCollectionID + "&pageIndex=1&pageSize=" + total;
                        String contactInfoAgain = HttpUtil.getPageSSL(contactInfoUrlAgain, params, headers);
                        LOGGER.info("== 获取成功 contactInfo==");

                        try {
                            Any data = JsonIterator.deserialize(contactInfoAgain).get("data");

                            JSONObject jsonData = new JSONObject();
                            jsonData.put("contacts", data.get("list").toString());

                            String contactUrl = uploadContact(order.getOrderNo(), jsonData.toString());
                            LOGGER.info("== 上传通讯录，得到地址 ==,url:{}", contactUrl);
                            infoMap.put("contactUrl", contactUrl);
                        } catch (Exception e) {
                            LOGGER.error("== 通讯录转换错误 ==", e);
                        }
                    } else {
                        contactUrlDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(contactUrlDetail);
                    }

                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        if (byKeyAndMerchantAndOrderNo == null) {
                            CeOrdersDetailEntity ordersDetailEntity = new CeOrdersDetailEntity()
                                    .setOrderNo(order.getOrderNo())
                                    .setMerchantCode(order.getMerchantCode())
                                    .setDataKey(k)
                                    .setDetailInfo(infoMap.get(k));
                            ordersDetailDao.insert(ordersDetailEntity);
                        } else {
                            byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                            ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                        }

                    });
                } else {
                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                        ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                    });
                }

                order.setDetailStatus(1);
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 程序处理有异常 ==", e);
                order.setDetailStatus(2);
                ordersDao.updateByPrimaryKey(order);
            }
        });

        LOGGER.info("== 程序处理完成 ==");
    }

    @Override
    public void compostCollectionData(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== compostCollectionData ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== compostCollectionData  没有需要同步的订单 ==，agentCode:{},syncStatus:{}", agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
            return;
        }

        LOGGER.info("== compostCollectionData  需要同步的订单 ==，size:{},account:{}", todayListBySyncStatusAndAgent.size(), agentAccount.getAccount());

        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                LOGGER.info("== 构建推送信息 基础信息 开始==,collectionNo:{},syncStatus:{}", order.getCollectionNo(), order.getSyncStatus());
                Any orderDetail = JsonIterator.deserialize(order.getOrderInfo());
                String appName = orderDetail.get("productName").toString();
                ClOrderReceiveRequest request = new ClOrderReceiveRequest()
                        .setOrderBillNo(order.getCollectionNo())
                        .setTradeNo(order.getCollectionNo())
                        .setProductType(appName)
                        .setAppName(appName)
                        .setOriginOrderNo(order.getOrderNo())
                        .setAccount(order.getAgentCode())
                        .setAccount_id(agentAccount.getId())
                        .setClientCode(order.getMerchantCode())
                        .setProductCode(appName)
                        .setUserCode(IdUtils.genId() + "");


                CeOrdersDetailEntity repaymentInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
                Any repaymentInfo = JsonIterator.deserialize(repaymentInfoDetail.getDetailInfo());
                String borrowCapital = new BigDecimal(repaymentInfo.get("loanAmount").toString()).divide(new BigDecimal(100)).toString();
                String actualAmount = new BigDecimal(repaymentInfo.get("actualAmount").toString()).divide(new BigDecimal(100)).toString();
                String paidAmount = new BigDecimal(repaymentInfo.get("paidAmount").toString()).divide(new BigDecimal(100)).toString();
                String repaymentAmount = new BigDecimal(repaymentInfo.get("repaymentAmount").toString()).divide(new BigDecimal(100)).toString();
                String balanceAmount = new BigDecimal(repaymentInfo.get("balanceAmount").toString()).divide(new BigDecimal(100)).toString();
                String overdueDays = repaymentInfo.get("overdueDays").toString();
                String serviceFee = new BigDecimal(repaymentInfo.get("serviceFee").toString()).divide(new BigDecimal(100)).toString();
//                String lateFee = repaymentInfo.get("serviceFee").toString();
                String overdueRatio = "0";
//                LOGGER.info("== 构建推送信息 计算逾期罚息利率 开始==,borrowCapital:{}，overdueDays:{}.lateFee:{}", borrowCapital, overdueDays, lateFee);
//                if (!overdueDays.equals("0")) {
//                    overdueRatio = new BigDecimal(lateFee).divide(new BigDecimal(overdueDays), 2, BigDecimal.ROUND_HALF_UP).divide(new BigDecimal(borrowCapital), 4, BigDecimal.ROUND_HALF_UP).toString();
//                }

                LOGGER.info("== 构建推送信息 订单信息 开始==,collectionNo:{}", order.getCollectionNo());
                ClOrderInputVo orderInputVo = new ClOrderInputVo()
                        .setBorrowType(1)
                        .setBorrowCapital(borrowCapital)
                        .setChannel(appName)
                        .setCapitalCode(appName)
                        .setInterest("0")
                        .setDeductAmount("0")
                        .setLateFeeRatio(overdueRatio)
                        .setServiceFee(serviceFee)
                        .setLateServiceFee("0")
                        .setReceivedCapital(actualAmount)
                        .setPaidAmount(paidAmount)
                        .setReceivedDate(DateUtil.getDate(new Date(repaymentInfo.get("loanTime").toLong() * 1000 - 9000000), "yyyy-MM-dd"))
                        .setRepaymentDate(DateUtil.getDate(new Date(repaymentInfo.get("repaymentTime").toLong() * 1000 - 9000000), "yyyy-MM-dd"))
                        .setRemainMoney(balanceAmount)
                        .setTotalMoney(repaymentAmount);

                request.setOrderInfo(orderInputVo);

                LOGGER.info("== 构建推送信息 个人信息 开始==,collectionNo:{}", order.getCollectionNo());
                CeOrdersDetailEntity personalInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "baseInfo", order.getOrderNo());
                Any personalInfoJson = JsonIterator.deserialize(personalInfo.getDetailInfo());

                String aadhaarNo = personalInfoJson.get("cid").toString();
                String pancardNo = personalInfoJson.get("panNumber").toString();
                String email = "no";
                String mobile = orderDetail.get("phone").toString();
                String name = personalInfoJson.get("name").toString();
                String state = "no";
                int gender = personalInfoJson.get("sex").toInt();
                int maritalStatus = 0;
                int education = 0;
                String address = personalInfoJson.get("address").toString();
                String pinCode = "no";
                String city = "no";
                String birthDay = personalInfoJson.get("birth").toString();

                CeOrdersDetailEntity contactInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactInfo", order.getOrderNo());
                List<Any> contactInfoJson = JsonIterator.deserialize(contactInfo.getDetailInfo()).asList();


                CeOrdersDetailEntity contactUrlEntity = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactUrl", order.getOrderNo());

                String parentName = "no";
                String parentPhone = "no";
                String friendName = "no";
                String friendMobile = "no";
                if (contactInfoJson.size() >= 2) {
                    parentName = contactInfoJson.get(0).get("name").toString();
                    parentPhone = contactInfoJson.get(0).get("mobile_number").toString();
                    friendName = contactInfoJson.get(1).get("name").toString();
                    friendMobile = contactInfoJson.get(1).get("mobile_number").toString();
                }


                CeOrdersDetailEntity iamges = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "images", order.getOrderNo());
                List<Any> anies = JsonIterator.deserialize(iamges.getDetailInfo()).asList();

                List<String> images = new ArrayList<>();
                anies.forEach(v -> {
                    images.add(v.toString());
                });

                ClUserInfoInputVo userInfoInputVo = new ClUserInfoInputVo()
                        .setUserLanguage("")
                        .setAadhaarNo(aadhaarNo)
                        .setPanCardNo(pancardNo)
                        .setAddress(address)
                        .setBirthday(birthDay)
                        .setCity(city)
                        .setEmail(email)

                        .setContact1Mobile(parentPhone)
                        .setContact1Name(parentName)
                        .setContact1Relative(1)

                        .setContact2Mobile(friendMobile)
                        .setContact2Name(friendName)
                        .setContact2Relative(6)

                        .setEducation(education)
                        .setKycNo(aadhaarNo)
                        .setMobile(mobile)

                        .setMarriedStatus(maritalStatus)
                        .setMarriedStatus(maritalStatus)
                        .setName(name)
                        .setPinCode(pinCode)
                        .setState(state)

                        .setSex(gender)
                        .setContactUrl(contactUrlEntity.getDetailInfo())
                        .setImages(images);

                request.setUserInfo(userInfoInputVo);

                LOGGER.info("== 构建推送信息 完成==,collectionNo:{}", order.getCollectionNo());

                CePushLogEntity pushLogEntity = pushLogDao.selectByCollectionNo(order.getCollectionNo());
                if (pushLogEntity == null) {
                    pushLogEntity = new CePushLogEntity()
                            .setCollectionNo(order.getCollectionNo())
                            .setDetailInfo(JsonStream.serialize(request))
                            .setStatus(1);
                    pushLogDao.insert(pushLogEntity);
                } else {
                    pushLogEntity.setDetailInfo(JsonStream.serialize(request));
                    pushLogDao.updateByPrimaryKey(pushLogEntity);
                }


                LOGGER.info("== 构建推送信息 保存信息完成==,collectionNo:{}", order.getCollectionNo());
                order.setSyncStatus(OrderSyncStatusEnum.data_ready.getStatus());
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 构建推送信息 发生异常==,collectionNo:{}", order.getCollectionNo(), e);
                order.setSyncStatus(OrderSyncStatusEnum.data_fail.getStatus());
                ordersDao.updateByPrimaryKey(order);
            }
        });

    }

    @Override
    public void pushDataToCollection(CeAgentAccountEntity agentAccount) {
        super.pushDataToCollection(agentAccount);
    }

    /**
     * 获取新的借贷信息的详细内容是需要 在这个方法执行之前的
     *
     * @param agentAccount
     */
    @Override
    public void checkOrdersPaidStatus(final CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 检查订单支付情况 ==");
        List<CeOrdersEntity> waitingPaidCheckOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.updated.getStatus());
        if (CollectionUtils.isEmpty(waitingPaidCheckOrders)) {
            LOGGER.info("== 检查订单支付情况 没有状态更新的订单==,size:{}", waitingPaidCheckOrders.size());
            return;
        }

        LOGGER.info("== 检查订单支付情况==,size:{}", waitingPaidCheckOrders.size());
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        Map<String, String> headers = getHeaders(agentAccount);
        Map<String, String> params = Maps.newHashMap();
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));

        waitingPaidCheckOrders.forEach(order -> {
            long time = DateUtil.getDate(DateUtil.getDate("yyyy-MM-dd") + " 02:30:00", "yyyy-MM-dd hh:mm:ss").getTime()/1000;
            String historyUrl;
            if (agentAccount.getStage().contains("d")) {
                historyUrl = merchant.getApiDomain() + "/cms/preCollection/tasks/history?pageIndex=1&pageSize=200&outTimeGte=" + time + "&outTimeLte=" + time;
            }else {
                historyUrl = merchant.getApiDomain() + "/cms/collection/tasks/history?pageIndex=1&pageSize=200";
            }
            String historyResult = HttpUtil.getPage(historyUrl,params, headers);
            if (JsonIterator.deserialize(historyResult).get("code").toInt() != 200) {
                LOGGER.error("== 已还款订单列表请求接口数据出错 ==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
                return;
            }
            List<Any> historyResultsList = JsonIterator.deserialize(historyResult).get("data").get("list").asList();
            LOGGER.info("== 已还款订单列表数量 ==,historyResultsList:{}", JsonStream.serialize(historyResultsList));

            boolean isRepay = false;
            int settledType=0;
            for (int i = 0; i < historyResultsList.size(); i++) {
                if (order.getOrderNo().equals(historyResultsList.get(i).get("orderID").toString())) {
                    isRepay = true;
                    settledType= historyResultsList.get(i).get("settledType").toInt();
                    break;
                }
            }
            if (isRepay) {
                LOGGER.info("== 订单已还款 ==,OrderNo:{}", order.getOrderNo());
                order.setSyncStatus(OrderSyncStatusEnum.need_pay_update.getStatus());
                order.setStatus(OrderStatusEnum.paid_update.getStatus());
                order.setRepayType(settledType);
                ordersDao.updateByPrimaryKey(order);
                return;
            }

            LOGGER.info("== 订单未还款，移除订单 ==,orderNo:{}", order.getOrderNo());
            order.setStatus(OrderStatusEnum.removed.getStatus());
            order.setSyncStatus(OrderSyncStatusEnum.need_remove.getStatus());
            ordersDao.updateByPrimaryKey(order);
        });


    }

    @Override
    public void updatePaidOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 开始同步有更新的数据到催收系统 ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_pay_update.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== 开始同步有更新的数据到催收系统 没有还款订单==");
            return;
        }

        LOGGER.info("== 开始同步有更新的数据到催收系统 有还款==,size:{}", todayListBySyncStatusAndAgent.size());
        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                CeOrdersDetailEntity repaymentInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
                Any repaymentInfo = JsonIterator.deserialize(repaymentInfoDetail.getDetailInfo());
                String paidAmount = repaymentInfo.get("paidAmount").toString().equals("") ? "0" : new BigDecimal(repaymentInfo.get("paidAmount").toString()).divide(new BigDecimal(100)).toString();
                ClRepaymentRequest request = new ClRepaymentRequest()
                        .setDeductAmount("0")
                        .setOrderBillNo(order.getCollectionNo())
                        .setPaidAmount(paidAmount)
                        .setPaidStatus(2)
                        .setPaidType(1)
                        .setRepayBizNo(IdUtils.genId() + "")
                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
                        .setTotalDeductAmount("0")
                        .setTotalPaidAmount(paidAmount)
                        .setTradeNo(order.getCollectionNo());

                HttpHeaders headers = new HttpHeaders();
                headers.set("Content-Type", "application/json;charset=utf-8");

                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl(), requestPush, String.class);
                String responseStr = responseEntity.getBody().toString();
                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl());
                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_success.getStatus());
                } else {
                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
                }
            } catch (Exception e) {
                LOGGER.error("=======  推送collection请求结果 error  ======", e);
                order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
            }
            ordersDao.updateByPrimaryKey(order);
        });


    }


    @Override
    public void updateRemovedOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("==  updateRemovedOrderToCollection 开始同步有更新的数据到催收系统 ==");
//        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_remove.getStatus());
//        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
//            LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 没有需要移除的订单==");
//            return;
//        }
//
//        LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 有数据需要移除==,size:{}", todayListBySyncStatusAndAgent.size());
//        todayListBySyncStatusAndAgent.forEach(order -> {
//            try {
//                CeOrdersDetailEntity repaymentInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
//                Any repaymentInfo = JsonIterator.deserialize(repaymentInfoDetail.getDetailInfo());
//                String paidAmount = repaymentInfo.get("paidAmount").toString().equals("") ? "0" : new BigDecimal(repaymentInfo.get("paidAmount").toString()).divide(new BigDecimal(100)).toString();
//                ClRepaymentRequest request = new ClRepaymentRequest()
//                        .setDeductAmount("0")
//                        .setOrderBillNo(order.getCollectionNo())
//                        .setPaidAmount(paidAmount)
//                        .setPaidStatus(2)
//                        .setPaidType(1)
//                        .setRepayBizNo(IdUtils.genId() + "")
//                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
//                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
//                        .setTotalDeductAmount("0")
//                        .setTotalPaidAmount(paidAmount)
//                        .setTradeNo(order.getCollectionNo());
//
//                HttpHeaders headers = new HttpHeaders();
//                headers.set("Content-Type", "application/json;charset=utf-8");
//
//                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
//                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl()_remove, requestPush, String.class);
//                String responseStr = responseEntity.getBody().toString();
//                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl()_remove);
//                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
//                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_success.getStatus());
//                } else {
//                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//                }
//            } catch (Exception e) {
//                LOGGER.error("=======  推送collection请求结果 error  ======", e);
//                order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//            }
//            ordersDao.updateByPrimaryKey(order);
//        });


    }

    @Override
    public void composeNote(CeCommentPushLogEntity ceCommentPushLogEntity) {
        ceCommentPushLogEntity.setStatus(1);
        commentPushLogDao.updateByPrimaryKey(ceCommentPushLogEntity);
    }


    @Override
    public boolean sendNote(CeCommentPushLogEntity ceCommentPushLogEntity) {

        HiRupeeCollectionTagEnum currentTag = HiRupeeCollectionTagEnum.RNR_V2;

        for (HiRupeeCollectionTagEnum e : HiRupeeCollectionTagEnum.values()) {
            if (e.getType().equals(ceCommentPushLogEntity.getTargetType())) {
                currentTag = e;
            }
        }
        LOGGER.info("== 开始同步催记到甲方 ==");
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceCommentPushLogEntity.getMerchantCode());
        CeAgentAccountEntity account = agentAccountDao.getByAgentCode(ceCommentPushLogEntity.getAgentCode());
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByOrderNo(ceCommentPushLogEntity.getOriginNo());
        Any orderInfo = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());
        try {
            String id = orderInfo.get("id").toString();
            Map<String, String> headers = getHeaders(account);
            JSONObject params = new JSONObject();
            params.put("contactPhone", orderInfo.get("phone").toString());
            params.put("contactPhoneType", 1);
//            params.put("actionMarkHitWhatsapp", currentTag.getWaStatus());
//            params.put("actionMarkPhone", currentTag.getpStatus());
            params.put("contactResult", currentTag.getState());
            params.put("remark", currentTag.getShortDesc());
            LOGGER.info("== HiRupee 开始同步催记到甲方D ==,params:{}", JsonStream.serialize(params));
            String noteUrl;
            if (account.getStage().contains("d")){
                noteUrl = ceMerchantEntity.getApiDomain() + "/cms/preCollection/tasks/item/" + id + "/records";
            }else {
                noteUrl = ceMerchantEntity.getApiDomain() + "/cms/collection/tasks/item/" + id + "/records";
            }
            String result = HttpUtil.postPageBody(noteUrl, headers, params.toString());
            LOGGER.info("== HiRupee 开始同步催记到甲方 ==,res:{}", result);

            if ("200".equals(JsonIterator.deserialize(result).get("code").toString())) {
                LOGGER.info("== 开始同步催记到甲方 success==");
                return true;
            } else {
                LOGGER.error("== 开始同步催记到甲方 error==");
            }

        } catch (Exception e) {
            LOGGER.error("== 开始同步催记到甲方 exception==", e);
        }
        return false;
    }

    @Override
    public String updateRepaymentLink(String collectionNo, boolean isReduce) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());
        Any orderInfoJson = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());
        String link = "No Link";
        Map<String, String> headers = getHeaders(accountEntity);
        JSONObject params = new JSONObject();
        params.put("paymentCodeType", 1);
        params.put("orderID", orderInfoJson.get("orderID").toString());
        params.put("repayAmount", 0);
        String url = ceMerchantEntity.getApiDomain() + "/cms/order/tasks/paymentCode";
        LOGGER.info("== 获取HiRupee还款链接 ==,url:{}", url);
        String result = HttpUtil.postPageBody(url, headers, params.toString());
        LOGGER.info("== 获取HiRupee还款链接 ==,url:{},res:{}", url, result);
        Any resultJson = JsonIterator.deserialize(result);
        if (resultJson.get("code").toInt() == 200) {
            link = resultJson.get("data").get("paymentCode").toString();
            LOGGER.info("== 获取还款链接 ==,link:{}", link);
        }
        CeRepaymentLinkEntity entity = new CeRepaymentLinkEntity();
        entity.setMerchantCode(ceMerchantEntity.getMerchantCode());
        entity.setAgentCode(accountEntity.getAgentCode());
        entity.setCollectionNo(ceOrdersEntity.getCollectionNo());
        entity.setStatus(0);
        entity.setOtherInfo("");
        entity.setPaymentUrl(link);
        repaymentLinkDao.insert(entity);
        return link;
    }

    @Override
    public String updateExtensionRepaymentLink(String collectionNo,boolean isOpen) {
        if(!apolloConfigUtil.isExtensionLinkOpen()){
            LOGGER.info("== 获取HiRupee展期链接不开放 ==");
            return "No Link";
        }else {
            if (!apolloConfigUtil.isExtensionLinkSwitch()){
                LOGGER.info("== 获取HiRupee展期链接管理员使用 ==");
                return "No Link";
            }
        }

        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByCollectionNo(collectionNo);
        CeAgentAccountEntity accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());
        Any orderInfoJson = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());

        String renewLink = "No Link";
        Map<String, String> headers = getHeaders(accountEntity);
        JSONObject params = new JSONObject();
        params.put("paymentCodeType", 3);
        params.put("orderID", orderInfoJson.get("orderID").toString());
        params.put("repayAmount", 0);
        String url = ceMerchantEntity.getApiDomain() + "/cms/order/tasks/paymentCode";
        LOGGER.info("== 获取HiRupee展期链接 ==,url:{}", url);
        String result = HttpUtil.postPageBody(url, headers, params.toString());
        LOGGER.info("== 获取HiRupee展期链接 ==,url:{},res:{}", url, result);
        Any resultJson = JsonIterator.deserialize(result);
        if (resultJson.get("code").toInt() == 200) {
            renewLink = resultJson.get("data").get("paymentCode").toString();
            LOGGER.info("== 获取展期链接 ==,link:{}", renewLink);
        }
        CeRepaymentLinkEntity entity = new CeRepaymentLinkEntity();
        entity.setMerchantCode(ceMerchantEntity.getMerchantCode());
        entity.setAgentCode(accountEntity.getAgentCode());
        entity.setCollectionNo(ceOrdersEntity.getCollectionNo());
        entity.setStatus(1);
        entity.setOtherInfo("");
        entity.setPaymentUrl(renewLink);
        repaymentLinkDao.insert(entity);
        return renewLink;
    }

    @Override
    public String addPaymentOrder(String orderNo, String fileName, String fileUrl, String utr, String remark, String amount) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getOneByOrderNo(orderNo);
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());
        CeAgentAccountEntity account = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        Any orderInfo = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());
        Map<String, String> headers = getHeaders(account);
        try {
            String uploadUrl=ceMerchantEntity.getApiDomain()+ "/cms/upload/img";
            RequestBody imgBody = RequestBody.create(MediaType.parse("application/octet-stream"),
                    getFile(fileUrl));
            String imageName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1) + ".jpeg";

            RequestBody body = new MultipartBody.Builder().setType(MediaType.parse("multipart/form-data"))
                    .addFormDataPart("file", imageName, imgBody)
                    .addFormDataPart("type","1")
                    .build();
            String uploadResult = HttpUtil.postFormData1(uploadUrl, headers, body);
            LOGGER.info("== HiRupee补单 ==,result:{}", uploadResult);
            String imageUrl = JsonIterator.deserialize(uploadResult).get("data").get("url").toString();
            String addPaymentOrderUrl = ceMerchantEntity.getApiDomain()+"/cms/order/tasks/item/utr";
            String preCollectionID;
            if (account.getStage().contains("d")){
                preCollectionID = orderInfo.get("preCollectionID").toString();
            }else {
                preCollectionID = orderInfo.get("collectionID").toString();
            }
            JSONObject params = new JSONObject();
            params.put("caseID",preCollectionID);
            params.put("utr",utr);
            params.put("url",imageUrl);
            String addPaymentResult = HttpUtil.postPageSsL(addPaymentOrderUrl, headers, params.toString());
            if (JsonIterator.deserialize(addPaymentResult).get("code").toInt() == 200) {//提交成功
                LOGGER.info("== HiRupee补单成功 ==,orderNo:{}", orderNo);
            } else {//重复提交
                LOGGER.info("== HiRupee补单失败 ==,orderNo:{}", orderNo);
            }
            return JsonIterator.deserialize(addPaymentResult).get("message").toString();
        }catch (Exception e){
            return e.getMessage();
        }
    }

    @Override
    public String queryPaymentOrderResult(String orderNo, String utr) {
        return "";
    }

    @Override
    public String checkOrdersPaid(String orderNo) {
        CeOrdersEntity ceOrdersEntity = ordersDao.getTodayOneByOrderNo(orderNo);
        CeAgentAccountEntity accountEntity = agentAccountDao.getByAgentCode(ceOrdersEntity.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceOrdersEntity.getMerchantCode());
        Any orderInfoJson = JsonIterator.deserialize(ceOrdersEntity.getOrderInfo());

        if (ceOrdersEntity.getStatus() == 1) {
            Map<String, String> headers = getHeaders(accountEntity);
            Map<String, String> params = Maps.newHashMap();
            String url = ceMerchantEntity.getApiDomain() + "/cms/collection/tasks/utrs/item/" + orderInfoJson.get("preCollectionID").toString();
            LOGGER.info("== 获取HiRupee补单结果 ==,url:{}", url);
            String result = HttpUtil.getPage(url, params, headers);
            LOGGER.info("== 获取HiRupee补单结果 ==,url:{},res:{}", url, result);
            Any resultJson = JsonIterator.deserialize(result);
            if (resultJson.get("code").toInt() == 200) {
                List<Any> list = resultJson.get("data").get("list").asList();//目前已还款的补单status为2
                LOGGER.info("== 获取HiRupee补单结果 ==,list:{}", JsonStream.serialize(list));
                return list.get(list.size() - 1).get("remark").toString();
            }
            return "Wait";
        }
        return "Paid";
    }

    public static File getFile(String url) throws Exception {
        //对本地文件命名
        String fileName = url.substring(url.lastIndexOf("/")+1,url.length());
        File file = null;

        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            file = File.createTempFile("net_url", fileName);
            //下载
            urlfile = new URL(url);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return file;
    }

    public static void main(String[] args) {
        try {
            HashMap<String, String> headers = Maps.newHashMap();
            headers.put("x-app-token","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NjEyMjQ5NzAsImlzcyI6IkkxMjEwIiwiYXBwZGF0YSI6eyJwaG9uZSI6IjMwMDAyIiwicGFzc3dvcmQiOiI2NjMxMWU5MTA2MmRlYWM3MGY0NGE4YzBlNWFlODI5M2IwOWQyZWMyNmNjNTc4N2FjZDVjNmZiM2VmODFkNmNiIn19.fGlKHwpnZZLS7OUBiwL4l3vTjzYipyWzAE_3iUsKvSY");
            headers.put("Content-Type","application/json");
            String fileUrl = "https://dc-oss2.oss-ap-south-1.aliyuncs.com/jy/pay-s/4a2486b42aad462d8d1b67ac787a0b7d_pay_screen_shot";
            String uploadUrl="https://oa-in.lion.ocid.xyz/cms/upload/img";
            RequestBody imgBody = RequestBody.create(MediaType.parse("application/octet-stream"),
                    getFile(fileUrl));
            String imageName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1) + ".jpeg";

            RequestBody body = new MultipartBody.Builder().setType(MediaType.parse("multipart/form-data"))
                    .addFormDataPart("file", imageName, imgBody)
                    .addFormDataPart("type","1")
                    .build();
            String uploadResult = HttpUtil.postFormData1(uploadUrl, headers, body);
            LOGGER.info("== HiRupee补单 ==,result:{}", uploadResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
